package com.archermind.style.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;

public class ImageUtil {
	public static BufferedImage resize(BufferedImage source, int targetW,
			int targetH, boolean isscale) {
		// targetW，targetH分别表示目标长和宽
		int type = source.getType();
		BufferedImage target = null;
		double sx = (double) targetW / source.getWidth();
		double sy = (double) targetH / source.getHeight();
		// 这里想实现在targetW，targetH范围内实现等比缩放。如果不需要等比缩放
		// 则将下面的if else语句注释即可
		if(isscale){//需要等比缩放
			if (sx > sy) {
				sx = sy;
				targetW = (int) (sx * source.getWidth());
			} else {
				sy = sx;
				targetH = (int) (sy * source.getHeight());
			}
		}
		if (type == BufferedImage.TYPE_CUSTOM) { // handmade
			ColorModel cm = source.getColorModel();
			WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
					targetH);
			boolean alphaPremultiplied = cm.isAlphaPremultiplied();
			target = new BufferedImage(cm, raster, alphaPremultiplied, null);
		} else
			target = new BufferedImage(targetW, targetH, type);
		Graphics2D g = target.createGraphics();
		// smoother than exlax:
		g.setRenderingHint(RenderingHints.KEY_RENDERING,
				RenderingHints.VALUE_RENDER_QUALITY);
		g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
		g.dispose();
		return target;
	}

	/**
	 * 另存图片
	 * @param oriImage		源文件
	 * @param width				宽度限制
	 * @param hight				高度限制
	 * @param isscale			是否保持比例
	 * @throws Exception
	 */
	public static void saveAsImage(File oriImage,String miniFilePath,
			int width, int hight,boolean isscale) throws Exception {
		BufferedImage srcImage;
		// String ex =
		// fromFileStr.substring(fromFileStr.indexOf("."),fromFileStr.length());
		String filePath = oriImage.getAbsolutePath();
		String imgType = "JPEG";
		if (filePath.toLowerCase().endsWith(".png")) {
			imgType = "PNG";
		}
		// System.out.println(ex);
		File saveFile = new File(miniFilePath);
		srcImage = ImageIO.read(oriImage);
		if (width > 0 || hight > 0) {
			srcImage = resize(srcImage, width, hight,isscale);
		}
		ImageIO.write(srcImage, imgType, saveFile);
	}

	public static Integer[] getDimension(File oriImage) throws IOException {
		BufferedImage srcImage = ImageIO.read(oriImage);
		return new Integer[]{srcImage.getWidth(),srcImage.getHeight()};
	}

	/**
	 * 另存图片
	 * @param fromFileStr		源文件
	 * @param w				宽度限制
	 * @param h				高度限制
	 * @throws Exception
	 */
	public static File zipImage(String fromFileStr,int w, int h) throws Exception {
		File fromFile = new File(fromFileStr);
		BufferedImage image = ImageIO.read(fromFile);
		if(image == null){
			return fromFile;
		}
		int srcWidth = image.getWidth(null);
		int srcHeight = image.getHeight(null);
		if (srcWidth*1.0 / srcHeight >= w*1.0 / h && srcWidth > w){
			h = (int) (srcHeight * w / srcWidth);
		}else if(srcWidth*1.0 / srcHeight < w*1.0 / h && srcHeight > h){
			w = (int) ( srcWidth * h / srcHeight);
		}else{
			h = srcHeight;
			w = srcWidth;
		}
		BufferedImage tag = new BufferedImage(w,h, BufferedImage.TYPE_INT_RGB);
		tag.getGraphics().drawImage(image, 0, 0, w, h, null);
		/** 压缩之后临时存放位置 */
		ImageIO.write(tag,"JPEG",fromFile);
		return fromFile;
	}

	//获取文件后缀.
    public static String getFileExt(MultipartFile file){
	    String fileName = file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf("."));
        return fileExt;
    }



	/**
	 * 验证图片是否可以转换
	 */
	private final static String CONST_IMAGE_TYPE = "|jpeg|jpg|bmp|png|gif|raw|";
	public static boolean checkImageType(String type){
		if(CONST_IMAGE_TYPE.indexOf(("|"+StringUtils.lowerCase(type)+"|"))!=-1){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 根据文件路径获取文件缩放图片路径
	 * @param srcPath
	 * @return
	 */
	public static String getMiniPath(String srcPath,String renamestr){
		String miniPath = "";
		if(srcPath != null && srcPath.length() > 0 && srcPath.lastIndexOf(".")!=-1){
			String type = srcPath.substring(srcPath.lastIndexOf(".")+1,srcPath.length());
			if(checkImageType(type)){
				miniPath = srcPath.substring(0,srcPath.lastIndexOf("."))+renamestr+"."+type;
			}
		}
		return miniPath;
	}

	public static void main(String argv[]) {
		try {
			// 参数1(from),参数2(to),参数3(宽),参数4(高)
//			ImageUtil.saveAsImage("/webdata/www/fhapp/img/tt.jpg",
//					"/webdata/www/fhapp/img/ttt_mini.jpg", 100,100, true);
		//	System.out.println(getMiniPath("/webdata/www/fhapp/img/test.jpg","_mini"));
			System.out.println("#12345678".substring(0,7));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}